package com.boruan.shengtangfeng.admin.controller;

import java.util.Date;
import java.util.List;

import com.boruan.shengtangfeng.core.dto.ModuleVideoDto;
import com.boruan.shengtangfeng.core.entity.*;
import com.boruan.shengtangfeng.core.service.IModuleVideoService;
import com.boruan.shengtangfeng.core.vo.mapper.QuestionVoMapper;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.boruan.shengtangfeng.admin.jwt.UserSubject;
import com.boruan.shengtangfeng.admin.jwt.util.JwtUtil;
import com.boruan.shengtangfeng.core.dao.IModuleQuestionDao;
import com.boruan.shengtangfeng.core.dto.ModuleDto;
import com.boruan.shengtangfeng.core.dto.QuestionDto;
import com.boruan.shengtangfeng.core.dto.mapper.ModuleDtoMapper;
import com.boruan.shengtangfeng.core.dto.mapper.QuestionDtoMapper;
import com.boruan.shengtangfeng.core.service.IModuleService;
import com.boruan.shengtangfeng.core.service.ILogService;
import com.boruan.shengtangfeng.core.service.IQuestionService;
import com.boruan.shengtangfeng.core.utils.GlobalReponse;
import com.boruan.shengtangfeng.core.vo.ModuleVo;
import com.boruan.shengtangfeng.core.vo.QuestionVo;
import com.boruan.shengtangfeng.core.vo.mapper.ModuleVoMapper;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * @author:twy
 * @Description:
 */
@SuppressWarnings(value = "all")
@RestController
@RequestMapping("/admin/module")
@Api(value = "", tags = {"NO:17 模块相关接口"})
@Slf4j
public class ModuleApi {
    @Autowired
    private IModuleService moduleService;
    @Autowired
    private ILogService logService;
    @Autowired
    private IQuestionService iQuestionService;
    @Autowired
    private IModuleQuestionDao moduleQuestionDao;
    @Autowired
    private SQLManager sqlManager;
    @Autowired
    private IModuleVideoService moduleVideoService;

    @GetMapping(value = "/pageModule")
    @ApiOperation(value = "NO:17-1 分页查看模块", notes = "")
    public GlobalReponse<PageQuery<ModuleVo>> pageModule(Module module,
                                                @RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                                                @RequestParam(value = "pageSize", defaultValue = "20") int pageSize) {
        PageQuery<Module> pageData = new PageQuery<Module>();
        pageData.setPageNumber(pageNo);
        pageData.setPageSize(pageSize);
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        moduleService.pageQuery(pageData, module);
        pageData.setList(ModuleVoMapper.MAPPER.toVo(pageData.getList()));
        return GlobalReponse.success().setData(pageData);
    }


    @GetMapping(value = "/getModuleTree")
    @ApiOperation(value = "NO:17-1 查看模块树", notes = "")
    public GlobalReponse<List<ModuleVo>> pageModule(Module module) {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        List<ModuleVo> list = moduleService.findModuleTree(module);
        return GlobalReponse.success().setData(list);
    }

//    @GetMapping(value = "/findModuleTree")
//    @ApiOperation(value = "NO:17-2 获取模块树", notes = "")
//    public GlobalReponse<List<ModuleVo>> findModuleTree() {
//        List<ModuleVo> list = moduleService.findModuleTree();
//        return GlobalReponse.success(list);
//    }


    @GetMapping(value = "/getModuleQuestions")
    @ApiOperation(value = "NO:14-4 查看可添加到模块的试题列表", notes = "")
    public GlobalReponse<QuestionVo> getModuleQuestions(@RequestParam(required = false) String title,
                                                         @RequestParam(required = false) Long moduleId,
                                                         @RequestParam(required = false) String kaodian,
                                                         @RequestParam(required = false) Integer type,
                                                         @RequestParam(required = false) Long categoryId1, @RequestParam(required = false) Long categoryId2,
                                                         @RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                                                         @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        PageQuery<Question> pageData = new PageQuery<Question>();
        pageData.setPageNumber(pageNo);
        pageData.setPageSize(pageSize);
        pageData.setPara("title", title);
        pageData.setPara("moduleId", moduleId);
        pageData.setPara("categoryId1", categoryId1);
        pageData.setPara("categoryId2", categoryId2);
        pageData.setPara("kaodian", kaodian);
        pageData.setPara("type", type);

        iQuestionService.getModuleQuestions(pageData);
        return GlobalReponse.success().setData(pageData);
    }


    /**
     * @return
     * @Descrition:模块内试题替换
     */

//    @CrossOrigin
//    @GetMapping(value = "/getType")
//    @ApiOperation(value = "NO:14-2 查看题型", notes = "")
//    public GlobalReponse<List<QuestionTypeVo>> getType(@RequestParam Long moduleId,
//                                                       @RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
//                                                       @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
//        PageQuery<QuestionType> pageData = new PageQuery<QuestionType>();
//        pageData.setList(questionTypeVoList);
//        return GlobalReponse.success(pageData);
//    }

    @PostMapping("/getQuestionsByModuleId")
    @ApiOperation(value = "NO:14-9 获取已添加到模块下的题目", notes = "")
    public GlobalReponse<PageQuery<Question>> getQuestionsByModuleId(@RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                                                                   @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                                                                   @RequestParam(value = "moduleId") Long moduleId,
                                                                     @RequestParam(required = false) String title,
                                                                     @RequestBody QuestionDto questionDto) {

        PageQuery<Question> pageData = new PageQuery<Question>();
        pageData.setPageNumber(pageNo);
        if(pageSize==0){
            pageSize=500;
        }
        pageData.setPageSize(pageSize);
        pageData.setPara("moduleId", moduleId);
        pageData.setPara("title", title);
        iQuestionService.pageQueryByModule(pageData, QuestionDtoMapper.MAPPER.toEntity(questionDto));

        return GlobalReponse.success(pageData);
    }

    @GetMapping(value = "/addModule")
    @ApiOperation(value = "NO:17-3 添加或者修改模块（是否传入id 存在id：修改 不存在id：新增）", notes = "")
    public GlobalReponse<Module> addModule(ModuleDto moduleDto) {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        Module module = ModuleDtoMapper.MAPPER.toEntity(moduleDto);
        ModuleVo vo = null;

        Log sysLog = new Log();
        if (module.getId() != null) {
            // 更新
            Module module1 = moduleService.findById(module.getId());
            if (module1 == null) {
                return GlobalReponse.fail("未查询到要更新的数据");
            }
            if (module.getGradeId() == null) {
                return GlobalReponse.fail("年级ID不能为空");
            }
            if (module.getSubjectId() == null) {
                return GlobalReponse.fail("学科ID不能为空");
            }
            module1.setName(module.getName());
            module1.setSubjectId(module.getSubjectId());
            module1.setGradeId(module.getGradeId());
            module1.setIcon(module.getIcon());
            module1.setDifficulty(module.getDifficulty());
            module1.setParentId(module.getParentId() == null ? 0 : module.getParentId());
            module1.setUpdateBy(userSubject.getId().toString());
            module1.setUpdateTime(new Date());
            module1.setType(module.getType());
            moduleService.save(module1);
            sysLog.setObjectId(module1.getId());
            sysLog.setContent("后台管理修改模块信息");
            sysLog.setOperateType(Log.OperateType.ADD);
            vo = ModuleVoMapper.MAPPER.toVo(module1);
        } else {
            // 添加
            if (module.getGradeId() == null) {
                return GlobalReponse.fail("年级ID不能为空");
            }
            if (module.getSubjectId() == null) {
                return GlobalReponse.fail("学科ID不能为空");
            }
            module.setParentId(module.getParentId() == null ? 0 : module.getParentId());
            Module search = new Module();
            search.setParentId(module.getParentId());
            Integer maxSequence = moduleService.getMaxSequence(search);
            if (maxSequence == null) {
                maxSequence = 0;
            }
            module.setQuestionCount(0L);
            module.setCompleteCount(0);
            module.setSort(maxSequence + 1);
            module.setIsDeleted(false);
            module.setScore(module.getScore());
            module.setCreateBy(userSubject.getId().toString());
            module.setCreateTime(new Date());
            module.setType(module.getType());
            moduleService.save(module);
            sysLog.setObjectId(module.getId());
            sysLog.setContent("后台管理添加模块信息");
            sysLog.setOperateType(Log.OperateType.UPDATE);
            vo = ModuleVoMapper.MAPPER.toVo(module);
        }
        try {
            sysLog.setCreateTime(new Date());
            sysLog.setOperater(userSubject.getId());
            sysLog.setLogType(Log.LogType.ADMIN);
            logService.save(sysLog);
        } catch (Exception e) {
            log.error("后台管理保存模块失败：{}", e.getMessage());
            return GlobalReponse.fail();
        }
        return GlobalReponse.success(vo);
    }

    @GetMapping(value = "/delete")
    @ApiOperation(value = "NO:17-4 删除模块", notes = "")
    public GlobalReponse delete(Long id) {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        Module module = moduleService.findById(id);
        module.setIsDeleted(true);
        module.setUpdateBy(userSubject.getId().toString());
        module.setUpdateTime(new Date());
        try {
            //判断是否存在子模块
            Module search = new Module();
            search.setParentId(id);
            int count = moduleService.findByCondition(search).size();
            if (count > 0) return GlobalReponse.fail("当前模块非叶子节点，不可删除");

            moduleService.save(module);
            Log sysLog = new Log();
            sysLog.setContent("模块管理删除模块信息");
            sysLog.setCreateTime(new Date());
            sysLog.setOperater(userSubject.getId());
            sysLog.setObjectId(userSubject.getId());
            sysLog.setLogType(Log.LogType.ADMIN);
            sysLog.setOperateType(Log.OperateType.DELETE);
            logService.save(sysLog);
            return GlobalReponse.success();
        } catch (Exception e) {
            log.error("模块管理删除模块失败:{}", e.getMessage());
            return GlobalReponse.fail();
        }
    }

    /**
     * @param id
     * @return
     * @Descrition:题目上移接口
     */
    @GetMapping(value = "/moveUp")
    @ApiOperation(value = "NO:17-5题目上移接口", notes = "")
    public GlobalReponse moveUp(Long id) {
        Module module1 = moduleService.findById(id);
        Integer sort1 = module1.getSort();
        if (sort1 == null) {
            return GlobalReponse.success("该id所对应的题目不存在");
        }
        if (sort1 == 1) {
            return GlobalReponse.success("该题目是第一个无法上移");
        }
        Module search = new Module();
        search.setParentId(module1.getParentId());
        search.setSort(sort1 - 1);
        search.setIsDeleted(false);
        Module module2 = moduleService.templateOne(search);
        Integer sort2 = (sort1 - 1);
        try {
            module1.setSort(sort2);
            module2.setSort(sort1);
            moduleService.save(module1);
            moduleService.save(module2);
        } catch (Exception e) {
            return GlobalReponse.fail();
        }
        return GlobalReponse.success();
    }

    /**
     * @return
     * @Descrition:题目下移接口
     */
    @GetMapping(value = "/moveDown")
    @ApiOperation(value = "NO:17-6题目下移接口", notes = "")
    public GlobalReponse moveDown(Long id) {
        Module module1 = moduleService.findById(id);
        Integer sort1 = module1.getSort();
        Module search = new Module();
        search.setParentId(module1.getParentId());
        search.setIsDeleted(false);
        Integer maxSequence = moduleService.getMaxSequence(search);

        if (sort1 == null) {
            return GlobalReponse.success("该id所对应的题目不存在");
        }
        if (sort1.equals(maxSequence)) {
            return GlobalReponse.success("该题目是最后一个无法下移");
        }
        search = new Module();
        search.setParentId(module1.getParentId());
        search.setIsDeleted(false);
        search.setSort(sort1 + 1);
        Module module2 = moduleService.templateOne(search);
        Integer sort2 = (sort1 + 1);
        try {
            module1.setSort(sort2);
            module2.setSort(sort1);
            moduleService.save(module1);
            moduleService.save(module2);
        } catch (Exception e) {
            e.printStackTrace();
            return GlobalReponse.fail();
        }
        return GlobalReponse.success();
    }


    /**
     * @return
     * @Descrition:模块内添加试题
     * @date:2020年3月2号
     */
    @PostMapping(value = "/addQuestions")
    @ApiOperation(value = "NO:17-7 模块内添加试题", notes = "")
    public GlobalReponse addQuestions(@RequestParam Long moduleId, @RequestBody List<Long> questionIdList) {

        UserSubject userSubject = JwtUtil.getCurrentJwtUser();

        moduleService.addQuestions(userSubject.getId(), moduleId, questionIdList);

        return GlobalReponse.success();
    }

    /**
     * @return
     * @Descrition:模块内删除试题
     */
    @PostMapping(value = "/removeQuestions")
    @ApiOperation(value = "NO:17-8 模块内批量删除试题", notes = "")
    public GlobalReponse removeQuestions(@RequestParam Long moduleId, @RequestBody List<Long> questionIdList) {

        UserSubject userSubject = JwtUtil.getCurrentJwtUser();

        moduleService.removeQuestions(userSubject.getId(), moduleId, questionIdList);

        return GlobalReponse.success();
    }

    /**
     * @return
     * @Descrition:从另一个模块导入试题
     */
    @GetMapping(value = "/importFormAnother")
    public GlobalReponse importFormAnother(@RequestParam Long currentId, @RequestParam Long sourceId) {

        UserSubject userSubject = JwtUtil.getCurrentJwtUser();

        return moduleService.importFormAnother(userSubject.getId(), currentId, sourceId);

    }


    /**
     * @param id
     * @return
     * @Descrition:题目上移接口
     */
    @GetMapping(value = "/moveUpQuestion")
    @ApiOperation(value = "NO:17-5模块中题目上移接口", notes = "")
    public GlobalReponse moveUpQuestion(ModuleQuestion moduleQuestion,@RequestParam Integer type) {
        ModuleQuestion module1 = moduleService.findByModuleId(moduleQuestion);
        Integer sort1 = module1.getSort();
        if (sort1 == null) {
            return GlobalReponse.success("该id所对应的题目不存在");
        }
        if (sort1 == 1) {
            return GlobalReponse.success("该题目是第一个无法上移");
        }

        ModuleQuestion module2 = moduleQuestionDao.searchUpOne(sort1,module1.getModuleId(), type);
        Integer sort2 = module2.getSort();
        try {
            module1.setSort(sort2);
            module2.setSort(sort1);
            moduleService.saveQuestion(module1);
            moduleService.saveQuestion(module2);

        } catch (Exception e) {
            return GlobalReponse.fail();
        }
        return GlobalReponse.success();
    }

    /**
     * @param id
     * @return
     * @Descrition:题目置顶接口
     */
    @GetMapping(value = "/moveOne")
    @ApiOperation(value = "NO:17-5置顶", notes = "")
    public GlobalReponse moveOne(ModuleQuestion moduleQuestion,@RequestParam Integer type) {
        ModuleQuestion module1 = moduleService.findByModuleId(moduleQuestion);
        Integer sort1 = module1.getSort();
        if (sort1 == null) {
            return GlobalReponse.success("该id所对应的题目不存在");
        }
        if (sort1 == 1) {
            return GlobalReponse.success("该题目是第一个无法上移");
        }

        ModuleQuestion module2 = moduleQuestionDao.searchOne(module1.getModuleId(), type);
        Integer sort2 = module2.getSort();
        try {
            module1.setSort(sort2);
            module2.setSort(sort1);
            moduleService.saveQuestion(module1);
            moduleService.saveQuestion(module2);

        } catch (Exception e) {
            return GlobalReponse.fail();
        }
        return GlobalReponse.success();
    }

    /**
     * @return
     * @Descrition:题目置尾接口
     */
    @GetMapping(value = "/moveMax")
    @ApiOperation(value = "NO:17-6置尾", notes = "")
    public GlobalReponse moveMax(ModuleQuestion moduleQuestion,@RequestParam Integer type) {
        ModuleQuestion module1 = moduleService.findByModuleId(moduleQuestion);
        Integer sort1 = module1.getSort();

        Integer maxSequence = moduleQuestionDao.getMaxSequence(moduleQuestion.getModuleId(), type);

        if (sort1 == null) {
            return GlobalReponse.success("该id所对应的题目不存在");
        }
        if (sort1.equals(maxSequence)) {
            return GlobalReponse.success("该题目是最后一个无法下移");
        }
        ModuleQuestion module2 = moduleQuestionDao.searchDown(module1.getModuleId(), type);
        Integer sort2 = module2.getSort();
        try {
            module1.setSort(sort2 + 1);
//            module2.setSort(sort1);
            moduleService.saveQuestion(module1);
//            moduleService.saveQuestion(module2);
        } catch (Exception e) {
            e.printStackTrace();
            return GlobalReponse.fail();
        }
        return GlobalReponse.success();
    }

    /**
     * @return
     * @Descrition:题目下移接口
     */
    @GetMapping(value = "/moveDownQuestion")
    @ApiOperation(value = "NO:17-6模块中题目下移接口", notes = "")
    public GlobalReponse moveDownQuestion(ModuleQuestion moduleQuestion,@RequestParam Integer type) {
        ModuleQuestion module1 = moduleService.findByModuleId(moduleQuestion);
        Integer sort1 = module1.getSort();

        Integer maxSequence = moduleQuestionDao.getMaxSequence(moduleQuestion.getModuleId(), type);

        if (sort1 == null) {
            return GlobalReponse.success("该id所对应的题目不存在");
        }
        if (sort1.equals(maxSequence)) {
            return GlobalReponse.success("该题目是最后一个无法下移");
        }
        ModuleQuestion module2 = moduleQuestionDao.searchDownOne(sort1,module1.getModuleId(), type);
        Integer sort2 = module2.getSort();
        try {
            module1.setSort(sort2);
            module2.setSort(sort1);
            moduleService.saveQuestion(module1);
            moduleService.saveQuestion(module2);
        } catch (Exception e) {
            e.printStackTrace();
            return GlobalReponse.fail();
        }
        return GlobalReponse.success();
    }


    @GetMapping(value = "/getModuleVideo")
    @ApiOperation(value = "NO:17-8 查看可添加到模块的视频列表", notes = "")
    public GlobalReponse<ModuleVideo> getModuleVideo(@RequestParam(required = false) String title,
                                                        @RequestParam(required = false) Long moduleId,
                                                        @RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                                                        @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        PageQuery<ModuleVideo> pageData = new PageQuery<ModuleVideo>();
        pageData.setPageNumber(pageNo);
        pageData.setPageSize(pageSize);
        pageData.setPara("title", title);
        pageData.setPara("moduleId", moduleId);
        moduleVideoService.getModuleVideo(pageData);
        return GlobalReponse.success().setData(pageData);
    }

    @CrossOrigin
    @PostMapping(value = "/saveModuleVideo")
    @ApiOperation(value = "NO:17-9 新增章节视频", notes = "")
    public GlobalReponse saveModuleVideo(@RequestBody ModuleVideoDto moduleVideoDto){
        UserSubject userSubject=JwtUtil.getCurrentJwtUser();
        moduleVideoDto.setVideo(moduleVideoDto.getVideo());
        moduleVideoDto.setTitle(moduleVideoDto.getTitle());
        if(StringUtils.isBlank(moduleVideoDto.getThumb())) {
            moduleVideoDto.setThumb(moduleVideoDto.getVideo()+"?x-oss-process=video/snapshot,t_7000,f_jpg,w_800,h_600,m_fast");
        }else{
            moduleVideoDto.setThumb(moduleVideoDto.getThumb());
        }
        moduleVideoService.addVideo(moduleVideoDto);
        return GlobalReponse.success();
    }

    @PostMapping("/getVideoByModuleId")
    @ApiOperation(value = "NO:17-10 获取已添加到模块下的视频", notes = "")
    public GlobalReponse<PageQuery<ModuleVideo>> getVideoByModuleId(@RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                                                                     @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                                                                     @RequestParam(value = "moduleId") Long moduleId,
                                                                     @RequestParam(required = false) String title,
                                                                     @RequestBody ModuleVideoDto moduleVideoDto) {

        PageQuery<ModuleVideo> pageData = new PageQuery<ModuleVideo>();
        pageData.setPageNumber(pageNo);
        if(pageSize==0){
            pageSize=500;
        }
        pageData.setPageSize(pageSize);
        pageData.setPara("moduleId", moduleId);
        pageData.setPara("title", title);
        moduleVideoService.pageQueryByModule(pageData,moduleVideoDto);

        return GlobalReponse.success(pageData);
    }

    @PostMapping(value = "/addVideos")
    @ApiOperation(value = "NO:17-11 模块内添加视频", notes = "")
    public GlobalReponse addVideos(@RequestParam Long moduleId, @RequestBody List<Long> videoIdList) {

        UserSubject userSubject = JwtUtil.getCurrentJwtUser();

        moduleService.addVideos(userSubject.getId(), moduleId, videoIdList);

        return GlobalReponse.success();
    }

    /**
     * @return
     * @Descrition:模块内删除视频
     */
    @PostMapping(value = "/removeVideos")
    @ApiOperation(value = "NO:17-12 模块内批量删除视频", notes = "")
    public GlobalReponse removeVideos(@RequestParam Long moduleId, @RequestBody List<Long> videoIdList) {

        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        moduleService.removeVideos(userSubject.getId(), moduleId, videoIdList);

        return GlobalReponse.success();
    }
}
